{% extends "base.html" %}

{% block title %}我的签到{% endblock %}

{% block head %}
{{ super() }}
<link href="{{ static_url('css/my.css') }}" rel="stylesheet" type="text/css">
{% endblock %}

{% block body %}
{{ utils.header(current_user) }}
<script src="{{ static_url('components/misc.js') }}"></script>
<section class="task", id="task section">
  <div class="container">
    <h2>
      我的签到
      <a href="/task/new" class="btn btn-default btn-xs modal_load glyphicon glyphicon-plus"></a>
      {% if adminflg %}
      <button type="button" class="btn btn-default modal_load" data-load-method="GET" href="/user/{{ userid }}/manage" title="管理用户">管理用户
      </button>
      <button type="button" class="btn btn-default modal_load" data-load-method="GET" href="/site/{{ userid }}/manage" title="管理网站">管理网站
      </button>
      {% endif %}
      <button type="button" class="btn btn-default modal_load" data-load-method="GET" href="/user/{{ userid }}/database" title="备份数据库">数据库
      </button>
      <button type="button" class="btn btn-default modal_load" data-load-method="GET" href="/util/toolbox/{{ userid }}" title="工具箱">工具箱
      </button>
    </h2>
    <div class="text-left" style="float:left;margin-right:5px;margin-bottom: 5px;">
      <span class="btn-group">
        <button type="button" class="btn btn-default modal_load" data-load-method="GET"
          href="/task/{{ userid }}/multi?op=disable" title="禁用多个任务">禁用
        </button>
        <button type="button" class="btn btn-default modal_load" data-load-method="GET"
          href="/task/{{ userid }}/multi?op=enable" title="启用多个任务">启用
        </button>
        <button type="button" class="btn btn-default modal_load" data-load-method="GET"
          href="/task/{{ userid }}/multi?op=delete" title="启用多个任务">删除
        </button>
        <button type="button" class="btn btn-default modal_load" data-load-method="GET"
          href="/task/{{ userid }}/multi?op=settime" title="定时多个任务">定时
        </button>
        <button type="button" class="btn btn-default modal_load" data-load-method="GET"
          href="/task/{{ userid }}/multi?op=setgroup" title="分组多个任务">分组
        </button>
      </span>
    </div>
    <div class="input-group margin-bottom-sm col-">
      <span class="input-group-addon"><i class="fa fa-search" aria-hidden="true"></i></span>
      <input id="search-input" class="search form-control input" placeholder="搜索" autocomplete="off" spellcheck="false" autocorrect="off" tabindex="1" data-column="all">
      <span class="input-group-addon btn btn-default"><span type="span" class="fa fa-times-circle reset" aria-hidden="true"> 清空</span></span>
    </div>
    <table id="task_list" class="table table-hover tablesorter">
      <thead>
        <tr>
          <th title="签到网站平台名称">任务名称</th>
          <th style="text-align:center" title="签到成功/失败次数">成/败</th>
          <th title="上次签到成功时间">上次成功</th>
          <th style="text-align:center" title="签到状态" nowrap="nowrap" >状态</th>
          <th title="预计下次签到时间">下次签到</th>
          <th style="text-align:center" title="签到操作区">操作</th>
        </tr>
      </thead>
      {% for group in taskgroups | sort(reverse=True) %}
      <tbody name="{{group}} tbody">
           
        <tr>
          <th colspan="6" title="{{group}} taskgroup"  style="background-color:rgb(215,237,251);text-align: center;">
            <input type="checkbox"  title="全选/反选" name="{{group}} checkbox" style="float:left" onclick="allTaskgroupChecked(this)">
            <text>{{group}} 分组</text> 
            <button style="float:right;padding: 1px 6px;"  title="隐藏/显示" name="{{group}} taskgroup" onclick="taskGroup.toggle(this)" class="dropup">
              <span class="caret"></span>
            </button>
          </th>
        </tr>

        {% for task in tasks | sort(reverse=True, attribute="ctime") %}
        {% if group == task._groups %}
        <tr class="{{group}} taskgroup">
          <td>
            <input type="checkbox"  name="{{task.id}}" class="{{group}} checkbox" style="display: inline; min-height: unset;" onclick="taskNode.toggle(this)">
            {% if task.disabled %}<span title="任务处于禁用状态,使用 (立即执行) 成功签到一次,即可解除." style="color:#ff7600;border-left:5px solid #ff7600;padding-left:5px;">[禁用]</span>{% endif %}
            {{ utils.tplname(task.tpl) if task.tpl else "[已删除]" }}

            {% if task.note %}
            -
              <code>
              {% if task.note | length > 15 %}
              <span data-toggle="popover" data-content="{{ task.note }}">{{ task.note | truncate(15, killwords=True, leeway=0) }}</span>
              {% else %} {{ task.note }} {% endif %}
              </code>
              {% endif %}
              
          </td>
          <td style="text-align:center;color: #cacaca;"><a style="color:#518cb9;" title="成功计次">{{ task.success_count }}</a> / <a style="color:#c15454;" title="失败计次">{{ task.failed_count }}</a></td>
          <td><span data-toggle="popover" data-content="{{ format_date(task.last_success,-8*60,True,False,True) if task.last_success else '从未' }}">{{ format_date(task.last_success) if task.last_success else '从未' }}</span></td>

          <td style="text-align:center">{{ my_status(task) }}</td>
          <!-- <td>{{ task.msg }}</td> -->
      
          <td><span data-toggle="popover" data-content="{{ format_date(task.next,-8*60,True,False,True) if task.next else '从未' }}">{{ format_date(task.next) if task.next else '从未' }}</span></td>

          <td style="text-align:center">
            <div class="btn-group btn-group-xs" role="group">
              {% if task.tpl %}
              <button type="button" class="btn btn-default modal_load" href="/task/{{ task.id }}/edit" title="修改签到数据">修改</button>
              {% else %}
              <button type="button" class="btn btn-default" data-method="POST" href="/task/{{ task.id }}/del" data-confirm="是否要删除任务?">删除</button>
              {% endif %}
              <button type="button" class="btn btn-default modal_load" data-load-method="POST" href="/task/{{ task.id }}/run" title="立即执行签到任务">执行</button>
              <a class="btn btn-default" href="/tpl/{{ task.tplid }}/edit?taskid={{ task.id }}" target="_blank" title="查看模板数据">模板</a>
              <button type="button" class="btn btn-default modal_load" data-load-method="GET" href="/task/{{ task.id }}/settime" title="修改执行时间">定时</button>
              <a type="button" class="btn btn-default" href="/task/{{ task.id }}/log" target="_blank" title="查看执行日志">日志</a>
              <button type="button" class="btn btn-default modal_load" data-load-method="GET" href="/task/{{ task.id }}/group" title="将任务分组">分组</button>
            </div>
          </td>
          
        </tr>
        {% endif %}
        {% endfor %}
      
      </tbody>   
      {% endfor %}
      
    </table>
    <div class="text-right">
      <a href="/tpls/public" class="btn btn-default">所有公开模板</a>
    </div>
  </div>
</section>

<section class="tpl" id="tplsection">
  <div class="container">
    <h2>
      我的模板
      <a href="/har/edit" class="btn btn-default btn-xs glyphicon glyphicon-plus" target="_blank"></a>
      <a class="btn btn-default" href="/subscribe/{{ userid }}/" target="_blank" title="查看公共模板">公共模板</a>
    </h2>
    <table id="tpl_list" class="table table-hover tablesorter">
      <thead>
        <tr>
          <th title="签到模板名称">模板名称</th>
          <th title="模板创建时间">创建时间</th>
          <th title="模板最近修改时间">最近修改</th>
          <th title="模板最近执行成功时间">最近成功</th>
          <th style="text-align:center" title="模板操作区">操作</th>
        </tr>
      </thead>
      <!-- <tbody> -->
      {% for tplgroup in tplgroups | sort(reverse=True) %}
      <tbody name="{{tplgroup}} tbody">
        <tr>
          <th colspan="5"  style="background-color:rgb(215,237,251);text-align: center;">
            <text>{{ tplgroup }} 分组</text>
            <button style="float:right;padding: 1px 6px;"  title="隐藏/显示" name="{{tplgroup}} tplgroup" onclick="tplGroup.toggle(this)" class="dropup">
              <span class="caret"></span>
            </button>
          </th>
        </tr>
        {% for tpl in tpls | sort(reverse=True, attribute="mtime") %}
        {% if tplgroup == tpl._groups %}
        <tr class="{{ tplgroup }} tplgroup" >
          <td>
            {% if  tpl.updateable == 1 %}
            <a class="btn btn-default btn-xs" href="/tpl/{{ tpl.id }}/edit?tplurl={{ tpl.tplurl | urlencode }}?tpldata={{ tpl.tpldata | urlencode }}" target="_blank" title="更新模板">更新
            </a>
            {% endif %}
            {{ utils.tplname(tpl) }}
    
            {% if tpl.fork %}<span>[fork]</span>{% endif %}-<kbd>{{ tpl.siteurl }}</kbd>
          </td>

          <td><span data-toggle="popover" data-content="{{ format_date(tpl.ctime,-8*60,True,False,True)}}">{{ format_date(tpl.ctime) }}</span></td>         
          <td><span data-toggle="popover" data-content="{{ format_date(tpl.mtime,-8*60,True,False,True)}}">{{ format_date(tpl.mtime) }}</span></td>
      
          <td>
            {% if tpl.last_success %}
            <span class="last_success" data-toggle="popover" data-content="{{ format_date(tpl.last_success,-8*60,True,False,True)}} ">{{ format_date(tpl.last_success) }}</span>
            {% else %}
            从未
            {% endif %}
          </td>

          <td style="text-align:center">
            <div class="btn-group btn-group-xs" role="group" aria-label="...">
              {% if tpl.lock %}
              [锁定]
              {% else %}
              <a class="btn btn-default" href="/tpl/{{ tpl.id }}/edit" target="_blank" title="编辑模板数据">编辑</a>
              <a class="btn btn-default " data-method="POST" href="/tpl/{{ tpl.id }}/del" data-confirm="是否要删除模板?" title="删除模板数据">删除</a>
              {% endif %}
              <button type="button" class="btn btn-default modal_load" href="/task/new?tplid={{ tpl.id }}" title="通过此模板新建签到">新建</button>
              <button type="button" class="btn btn-default modal_load" href="/tpl/{{ tpl.id }}/push" title="发布自己创建的模板">发布</button>
              <button type="button" class="btn btn-default modal_load" data-load-method="GET" href="/tpl/{{ tpl.id }}/group" title="将模板分组">分组</button>
            </div>
          </td>
        
        {% endif %}
        {% endfor %}
      </tbody>
      {% endfor %}
      
    </table>
    <div class="text-right">
      <a href="/pushs" class="btn btn-default">我的发布请求</a>
    </div>
  </div>
</section>

<script>
  $(function() {
    $('[data-toggle=popover]').popover({
      trigger: 'hover'
    });
  })
</script>

<script>
  function checkboxOnclick(checkbox){
    var tasknodes = document.getElementsByClassName(checkbox.name);
    for (i = 0; i < tasknodes.length; i++) { 
      if (checkbox.checked == true){
        $(tasknodes[i]).hide();
      }else{
        $(tasknodes[i]).show();
      }
    }
  }
</script>
<script src="{{ static_url('components/mutil_op.js') }}"></script>

<script>
  /**
   * 全选/反选
   * 
   **/
  function allTaskgroupChecked(checkbox){
    var tmp = checkbox.name
    var tasknodes = document.getElementsByClassName(tmp);
    if (tasknodes.length > 0){
        for (i = 0; i < tasknodes.length; i++) { 
          if(checkbox.checked){
            tasknodes[i].checked = true
          }
          else {
            tasknodes[i].checked = false
          }
          taskNode.toggle(tasknodes[i], true)
        }
    } 
  }

</script>

<script>
  const taskNode = {
    selectedTaskNodesJSON: '{}',

    get selectedTaskNodes() {
      return this.getSelectedTaskNodes()
    },

    set selectedTaskNodes(val) {
      this.setSelectedTaskNodes(val)
    },

    getSelectedTaskNodes: function(){
      if(this.selectedTaskNodesJSON == '{}'){
        if (typeof(sessionStorage.selectedtask) != "undefined"){
          this.selectedTaskNodesJSON = sessionStorage.selectedtask
        }
      }
      return JSON.parse(this.selectedTaskNodesJSON)
    },

    setSelectedTaskNodes: function(val){
      this.selectedTaskNodesJSON = JSON.stringify(val)
      sessionStorage.selectedtask=JSON.stringify(val)
    },

    toggle: function(taskNode, uncheck) {
      let _selectedTaskNodes = this.selectedTaskNodes
      _selectedTaskNodes[taskNode.name] =taskNode.checked
      this.selectedTaskNodes = _selectedTaskNodes
      if(!uncheck) {
        (typeof setTaskGroupChecked == 'function') && setTaskGroupChecked(taskNode.className)
      }
    },


    init: function() {
      let _selectedTaskNodes = this.selectedTaskNodes
      let _classNames= {}
      for (let key in _selectedTaskNodes){
        let tasknodes = document.getElementsByName(key);
        if (tasknodes.length > 0){
          tasknodes[0].checked = _selectedTaskNodes[key]
          // 将已选中的tasknode的className 存储在_classNames中
          if(_selectedTaskNodes[key]) {
            _classNames[tasknodes[0].className] = true
          }
        }
      }

      for(let key in _classNames){
        (typeof setTaskGroupChecked == 'function') && setTaskGroupChecked(key)
      }
    }

  }

  /**
   *  修改全选按钮样式
   *  在taskNode.init()之前加载
   * 
   **/
   function setTaskGroupChecked(className){
    let _eles = document.getElementsByName(className)
    let _nodeGroupChecked
    for(let i=0; i<_eles.length; i++) {
      if(_eles[i].nodeName.toLowerCase() == 'input' &&
        _eles[i].getAttribute('type') == 'checkbox'
      ){
        _nodeGroupChecked = _eles[i]
      }
    }
    if(typeof _nodeGroupChecked == 'undefined') return;
    let _checkedNum = 0
    const _taskNodes = document.getElementsByClassName(className)

    for(key in _taskNodes) {
      if(_taskNodes[key].checked == true) {
        _checkedNum++
      }
    }

    if(_checkedNum == _taskNodes.length) {
      _nodeGroupChecked.indeterminate = false;
      _nodeGroupChecked.checked = true;
    }else if(_checkedNum > 0) {
      _nodeGroupChecked.indeterminate = true;
      _nodeGroupChecked.checked = false;
    }else {
      _nodeGroupChecked.indeterminate = false;
      _nodeGroupChecked.checked = false;
    }
  }

  // 页面加载后初始化
  taskNode.init()

</script>

<script>
  /**
   * 创建一个用于控制group隐藏显示的对象
   * 
   * storage_HiddenGroupsName: 存储在localStorage中的隐藏Groups变量的名
   **/
  function createGroupObj(storage_HiddenGroupsName) {
    if(typeof storage_HiddenGroupsName != 'string' && storage_HiddenGroupsName.strim() != storage_HiddenGroupsName) {
      throw new Error('参数storageHiddenGroupsName类型必须为string，且不能为空')
    }

    return {
      hiddenGroupsJSON: '{}',
      _localStorageName: storage_HiddenGroupsName,
      get hiddenGroups() {
        return this.getHiddenGroups()
      },

      set hiddenGroups(val) {
        this.setHiddenGroups(val)
      },

      getHiddenGroups: function(){
        if(this.hiddenGroupsJSON == '{}'){
          if (typeof(window.localStorage[this._localStorageName]) != "undefined"){
            this.hiddenGroupsJSON = window.localStorage[this._localStorageName];
          }
        }
        return JSON.parse(this.hiddenGroupsJSON)
      },

      setHiddenGroups: function(val){
        this.hiddenGroupsJSON = JSON.stringify(val)
        window.localStorage[this._localStorageName]=JSON.stringify(val)
      },

      toggle: function(that){
        let groupName = that.name
        let _hiddenGroups = this.hiddenGroups
        if(typeof _hiddenGroups[groupName] != 'boolean') {
          _hiddenGroups[groupName] = false
        }
        _hiddenGroups[groupName] = !_hiddenGroups[groupName]
        this.nodesDisplay(groupName, !_hiddenGroups[groupName])
        this.hiddenGroups = _hiddenGroups
        // 三角符号变动
        if(that.className.includes('dropup')) {
          that.className = that.className.replaceAll('dropup','')
        }else {
          that.className = that.className.replace(/^\s+|\s+$/gm, '') + ' dropup'
        }
      },

      nodesDisplay: function(groupName, bool) {
        // bool: true时显示，false时隐藏
        let tasknodes = document.getElementsByClassName(groupName);
        if (tasknodes.length > 0){
          for (i = 0; i < tasknodes.length; i++) { 
            $(tasknodes[i]).toggle(bool);
          }
        }

      },

      init: function(){
        let _hiddenGroups = this.hiddenGroups
        for (let key in _hiddenGroups){
          this.nodesDisplay(key, !_hiddenGroups[key])
          if(_hiddenGroups[key]) {
            // $('input[type="checkbox"][name="'+key+'"]').prop('checked', _hiddenGroups[key])
            let _hiddenButton = document.getElementsByName(key)[0]
            _hiddenButton.className = _hiddenButton.className.replaceAll('dropup','')
          }
        }
  
      }
    }
  }
  const taskGroup = createGroupObj('HiddenTaskGroups')
  // 页面加载后初始化
  taskGroup.init()
</script>

<script>
  const tplGroup = createGroupObj('HiddenTplGroups')
  tplGroup.init()
  // const tplGroup = new taskGroup()

</script>

<script>
  $(function () {
    // Extend the themes to change any of the default class names
    $.tablesorter.themes.bootstrap = {
      // these classes are added to the table. To see other table classes available,
      // look here: http://getbootstrap.com/css/#tables
      table        : 'table table-hover',
      caption      : 'caption',
      // header class names
      header       : 'bootstrap-header', // give the header a gradient background (theme.bootstrap_2.css)
      sortNone     : '',
      sortAsc      : '',
      sortDesc     : '',
      active       : '', // applied when column is sorted
      hover        : '', // custom css required - a defined bootstrap style may not override other classes
      // icon class names
      icons        : '', // add "bootstrap-icon-white" to make them white; this icon class is added to the <i> in the header
      iconSortNone : 'bootstrap-icon-unsorted', // class name added to icon when column is not sorted
      iconSortAsc  : 'glyphicon glyphicon-chevron-up', // class name added to icon when column has ascending sort
      iconSortDesc : 'glyphicon glyphicon-chevron-down', // class name added to icon when column has descending sort
      filterRow    : '', // filter row class; use widgetOptions.filter_cssFilter for the input/select element
      footerRow    : '',
      footerCells  : '',
      even         : '', // even row zebra striping
      odd          : ''  // odd row zebra striping
    };
    $("#task_list,#tpl_list").tablesorter({
      theme: "bootstrap",
      // sortList:[[4,1],[2,0]],
      headers:{
        0:{sorter: false},
        1:{sorter: false},
        2:{sorter: false},
        3:{sorter: false},
        4:{sorter: false},
        5:{sorter: false, parser:false},
      },
      headerTemplate : '{content} {icon}', // needed to add icon for jui theme
      widgets : ['uitheme', 'filter'],
      widgetOptions : {
        // using the default zebra striping class name, so it actually isn't included in the theme variable above
        // this is ONLY needed for bootstrap theming if you are using the filter widget, because rows are hidden
        // zebra : ["even", "odd"],
        // class names added to columns when sorted
        // reset filters button
        filter_reset : ".reset",
        filter_external : '.search',
        filter_columnFilters: false,
        // extra css class name (string or array) added to the filter element (input or select)
        filter_cssFilter: "form-control"
        // set the uitheme widget to use the bootstrap theme class names
        // this is no longer required, if theme is set
        // ,uitheme : "bootstrap"
      }
    });
  })
</script>

{% include 'LeftFuncBtn.html' %}
{{ utils.modal_load() }}
{{ utils.apost() }}
{% endblock %}
